package org.yystory.ui;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.yystory.dataobject.StoryObject;
import org.yystory.entity.Story;
import org.yystory.service.StoryService;
import org.yystory.utility.ErrorParser;

import com.alibaba.fastjson.JSON;

public class StoryListServlet extends HttpServlet {

	private static final long serialVersionUID = 4643815585479097767L;

	public StoryListServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	private void response(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			Date date = sdf.parse(request.getParameter("date"));
			Story[] stories = StoryService.list(date);
			List<StoryObject> list = new ArrayList<StoryObject>();
			for (Story story : stories) {
				StoryObject object = new StoryObject();
				object.setName(story.getName());
				object.setStoryId(story.getId());
				object.setUserId(story.getUserId());
				object.setDate(story.getDate());
				list.add(object);
			}
			response.getWriter().print(JSON.toJSONString(list));
			response.getWriter().close();
		} catch (Exception e) {
			response.getWriter().print(
					ErrorParser.parseError("StoryListServlet", e.getClass()
							.getName() + ":" + e.getMessage()));
			response.getWriter().close();
		}
	}
}
